package com.wolfalpha.utron.utils;

import java.lang.reflect.Type;
import java.util.List;

import android.util.Log;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

public class JsonUtils {
    // 解析多个对象组合
    public static <T> T parasesJson(String json, Class<T> c) {
        try {
            Type listType = new TypeToken<List<T>>() {
            }.getType();
            Gson gson = new Gson();
            Log.d("JsonUtil", gson.fromJson(json, listType).toString());
            return gson.fromJson(json, listType);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    // 解析单个对象
    public static <T> T paraseJson(String json, Class<T> c) {
        try {
            Gson gson = new Gson();
            return gson.fromJson(json, c);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String getData(String json) {
        try {
            while (json.startsWith("\ufeff")) json = json.substring(1);
            JSONObject msg = new JSONObject(json);

            return msg.get("data").toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static int getRet(String json) {
        try {
            while (json.startsWith("\ufeff")) json = json.substring(1);
            JSONObject msg = new JSONObject(json);
            return msg.getInt("ret");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return 400;
    }

    public static String getMsg(String json) {
        try {
            while (json.startsWith("\ufeff")) json = json.substring(1);
            JSONObject msg = new JSONObject(json);
            return msg.get("msg").toString();
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return "";
    }
}
